<?php
namespace App\Utils\Other\Message;

use App\Constants\Message\SmsCode;
use App\Exception\InternalException;
use App\Utils\Http\Request;
use App\Utils\Other\Message\Sms\Chuanglan;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Collection\Arr;
use Psr\Log\LoggerInterface;
use function Hyperf\Config\config;
use function Hyperf\Support\make;

class App
{
    /**
     * 配置
     * @var array|mixed
     */
    protected array $config;

    /**
     * 应用配置
     * @var array
     */
    protected array $appConfig;

    /**
     * 日志
     * @var LoggerInterface
     */
    protected LoggerInterface $logger;

    public function __construct(
        protected Request $request,
        LoggerFactory $loggerFactory
    )
    {
        $this->config = config('message');
        $this->logger = $loggerFactory->get();
    }

    /**
     * 获取配置
     * @return mixed
     */
    protected function getConfig()
    { }

    /**
     * 请求
     * @param array $params
     * @return mixed
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function request($params=[])
    {
        $response = json_decode($this->request->post($this->appConfig['url'], $params, true), true);

        return $this->response($response);
    }

    /**
     * 响应
     * @param $response
     * @return mixed
     */
    protected function response($response)
    {
        if (is_null($response) || false === $response) {
            $this->logger->error('没有返回报文');
            throw new InternalException('No response message');
        } elseif (Arr::get($response, 'code')) {
            $this->logger->error("CODE:[{$response['code']}]Message:[{$response['errorMsg']}]");
            throw new InternalException('No response message');
        }
        return $response;
    }

    /**
     * 发送信息
     * @param string $account
     * @param string $msg
     * @return mixed
     */
    public function handle(string $account, string $msg, int $type=SmsCode::TYPE_MOBILE)
    {
        $send = match ($type) {
            SmsCode::TYPE_MOBILE => make(Chuanglan::class)
        };

        return $send->send($account, $msg);
    }
}